<?php
namespace app\beautiful\controller\miniapp\member\goods;
use app\BaseController;
use app\beautiful\model\mall\FreightTemplateModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\setting\SendCityModel;
use app\beautiful\model\setting\SendKuaidiModel;
use app\beautiful\model\setting\SendSelfModel;
use app\common\model\ShopModel;

class Send extends BaseController{

    /**
     *判断地址是否符合
     */
    public function getAddressResult(){
        $send_type = $this->request->param('send_type/d',0);//配送方式：1快递2自提3同城
        $long = $this->request->param('lng/f');
        $lat = $this->request->param('lat/f');
        $detail=[
            'result'=>1
        ];
        if($send_type == 3){
            if($long <= 0 || $lat <= 0) return $this->error ('参数错误');

            $city_setting = SendCityModel::where([['shop_id','=',$this->request->shopId]])->json(['send_scope','order_send_time','ladder_freight_distance','ladder_freight_price'],true)->find();

            $send_scope = $city_setting->send_scope;
            if($send_scope){
                if(!empty($send_scope['lng']) && !empty($send_scope['lat'])){
                    $url = "https://apis.map.qq.com/ws/coord/v1/translate";
                    $url = $url."?key=LANBZ-MSKK4-Q2FUB-XCOEP-KB4V5-RDFCV&type=3&locations={$send_scope['lat']},{$send_scope['lng']}";
                    $res = https_curl($url,[]);
                    if(empty($res['status'])){
                        $send_scope['lng']=$res['locations'][0]['lng'];
                        $send_scope['lat']=$res['locations'][0]['lat'];
                    }
                }
                $distance = round(getDistance($long,$lat,$send_scope['lng'],$send_scope['lat']));
                if($distance > $send_scope['distance']*1000){
                    $detail=[
                        'result'=>0
                    ];
                }
            }
        }
        return $this->success(['detail'=>$detail]);

    }
    /**
     *获取配送时间
     */
    public function getSendTime(){
        $send_type = $this->request->param('send_type/d',0);//配送方式：1快递2自提3同城

        $detail =$day_arr= $week_arr= [];

        if($send_type == 2) {
            $self_setting = SendSelfModel::where([['shop_id', '=', $this->request->shopId]])->json(['order_self_time', 'order_time_slot'], true)->find();
            if ($self_setting) {
                //开启预约配送
                if($self_setting->open_order_self) {

                    $week_arr = [];
                    $order_self_time = $self_setting->order_self_time;
                    foreach ($order_self_time as $key => $value) {
                        foreach ($value['week'] as $k => $v) {
                            $week_arr[] = [
                                'week' => $v,
                                'start_time' => $value['start_time'],
                                'end_time' => $value['end_time']
                            ];
                        }
                    }
                    $open_order_day=empty($self_setting->open_order_day)?7:$self_setting->open_order_day;
                    $day_arr=$this->open_order_day($open_order_day,$week_arr);
                    $order_time_slot=$self_setting->order_time_slot;
                    foreach ($day_arr as &$v){
                        $day_time=$this->day_time($v['time'],$order_time_slot,$v['date']);
                        $v['day_time']=$day_time;
                    }
                }

                $detail = [
                    'open_order_self' => $self_setting->open_order_self,
                    'open_order_day' => $self_setting->open_order_day,
                    'order_time_slot' => $self_setting->order_time_slot,
                    'week'=>$week_arr,
                    'day_arr'=>$day_arr
                ];

            }
        }


        if($send_type == 3) {
            $city_setting = SendCityModel::where([['shop_id', '=', $this->request->shopId]])->json(['order_send_time', 'order_time_slot', 'forward_order_send'], true)->find();
            if ($city_setting) {
                //开启预约配送
                if($city_setting->open_order_send) {

                    $week_arr = [];
                    $order_send_time = $city_setting->order_send_time;
                    foreach ($order_send_time as $key => $value) {
                        foreach ($value['week'] as $k => $v) {
                            $week_arr[] = [
                                'week' => $v,
                                'start_time' => $value['start_time'],
                                'end_time' => $value['end_time']
                            ];
                        }
                    }
                    $open_order_day=empty($city_setting->open_order_day)?7:$city_setting->open_order_day;
                    $forward_order_send=$city_setting->forward_order_send;
                    $forward_time=0;
                    if($forward_order_send['forward_order_open']==1){//提前预约开启
                        if($forward_order_send['type']==1){//分钟
                            $forward_time=$forward_order_send['number']*60;
                        }elseif ($forward_order_send['type']==2){//小时
                            $forward_time=$forward_order_send['number']*60*60;
                        }elseif ($forward_order_send['type']==3){//天
                            $forward_time=$forward_order_send['number']*60*60*24;
                        }
                    }
                    $day_arr=$this->open_order_day($open_order_day,$week_arr,$forward_time);
                    $order_time_slot=$city_setting->order_time_slot;
                    foreach ($day_arr as &$v){
                        $day_time=$this->day_time($v['time'],$order_time_slot,$v['date'],$v['time_now']);
                        $v['day_time']=$day_time;
                    }
                }

                $detail = [
                    'open_order_send' => $city_setting->open_order_send,
                    'open_order_day' => $city_setting->open_order_day,
                    'order_time_slot' => $city_setting->order_time_slot,
                    'forward_order_send' => $city_setting->forward_order_send,
                    'week'=>$week_arr,
                    'day_arr'=>$day_arr
                ];

            }
        }

        return $this->success(['detail'=>$detail]);
    }


    /**
     *获取配送时间
     */
    public function getSendTimeOld(){
        $send_type = $this->request->param('send_type/d',0);//配送方式：1快递2自提3同城

        $detail = $week_arr= [];
        if($send_type == 3) {
            $city_setting = SendCityModel::where([['shop_id', '=', $this->request->shopId]])->json(['order_send_time', 'order_time_slot', 'forward_order_send'], true)->find();
            if ($city_setting) {
                //开启预约配送
                if($city_setting->open_order_send){
//                    //根据星期数排序
//                    array_multisort($week_arr, SORT_ASC, $order_send_time);
//                    //只获取预约档期（几天）的值
//                    array_splice($order_send_time,$city_setting->open_order_day);
                    $week_arr = [];
                    $order_send_time = $city_setting->order_send_time;

                    foreach ($order_send_time as $key=>$value){
                        foreach ($value['week'] as $k=>$v){
                            $week_arr[] = [
                                'week'=>$v,
                                'start_time'=>$value['start_time'],
                                'end_time'=>$value['end_time']
                            ];
                        }
                    }
                }

                $detail = [
                    'open_order_send' => $city_setting->open_order_send,
                    'open_order_day' => $city_setting->open_order_day,
                    'order_time_slot' => $city_setting->order_time_slot,
                    'forward_order_send' => $city_setting->forward_order_send,
                    'week'=>$week_arr
                ];
            }
        }

        return $this->success(['detail'=>$detail]);
    }

    /**
     *获取某天配送时间
     */
    public function getDaySendTime(){
        $today=date("Y-m-d",$this->request->time());
        $send_type = $this->request->param('send_type/d',0);//配送方式：1快递2自提3同城

        $day=$this->request->param('day');

        if(empty($day)) return $this->error('请选择预约日期');

        if(false === $day_unix=strtotime($day.' 00.00.00')) return $this->error('请选择预约日期');

        if($day<$today) return $this->error('预约日期不能低于今天');

        $week_arr = $detail = [];
        if($send_type == 3) {
            //开启预约配送
            $city_setting = SendCityModel::where(['shop_id'=> $this->request->shopId,'open_order_send'=>1])->json(['order_send_time', 'order_time_slot', 'forward_order_send'], true)->find();

            if ($city_setting) {

                $order_send_time = $city_setting->order_send_time;

                foreach ($order_send_time as $k=>$v){
                    $week_arr[$v['week']]=$v['week'];
                    $order_send_time[$v['week']]=$v;
                }

                if(!in_array(date('w',$day_unix),$week_arr)) return $this->error('选的日期不能进行预约');

                if($order_send_time[date('w',$day_unix)]){
                    $detail=[
                        'order_send_time'=>$order_send_time[date('w',$day_unix)],
                        'order_time_slot'=>$city_setting->order_time_slot
                    ];
                }
            }

        }

        return $this->success(['detail'=>$detail]);
    }
    /**
     * 获取开启的配送方式
     */
    public function getSendType(){
        $kuaidi_is_open = $self_is_open = $city_is_open = 0;

        
//        $kuaidi_setting = SendKuaidiModel::where([['shop_id', '=', $this->request->shopId]])->find();
        $kuaidi_setting = FreightTemplateModel::where([['shop_id', '=', $this->request->shopId]])->find();
        if($kuaidi_setting->is_open>0) $kuaidi_is_open = 1;
        
        $self_setting = SendSelfModel::where([['shop_id', '=', $this->request->shopId]])->find();
        if($self_setting->is_open>0) $self_is_open = 1;
        
        $city_setting = SendCityModel::where([['shop_id','=',$this->request->shopId]])->find();
        if($city_setting->is_open>0) $city_is_open = 1;

        $shop = ShopModel::where([['shop_id', '=', $this->request->shopId]])->find();

        $detail =[
            'kuaidi_is_open'=>$kuaidi_is_open,
            'self_is_open'=>$self_is_open,
            'city_is_open'=>$city_is_open,
            'default_send_type'=>$shop->default_send_type
        ];
        return $this->success(['detail'=>$detail]);
        
    }

    /**
     *获取配送费
     */
    public function getFreightInfo(){
        $send_type = $this->request->param('send_type/d',0);//配送方式：1快递2自提3同城
//        $goods_list = $this->request->param('goods_list');
//        $lng = $this->request->param('lng/f');
//        $lat = $this->request->param('lat/f');

//        if($lng <= 0 || $lat <= 0) return $this->error ('参数错误');
        if($send_type <= 0) return $this->error ('参数错误');
//        if($send_type <= 0 || empty($goods_list)) return $this->error ('参数错误');
//        $member=$this->request->member;
//
//        if($member->level_id>0){
//
//        }
        $detail = [];
//        $origin_price = $vip_price = $freight = 0.00;
//        $goods_list_arr = json_decode($goods_list,true);
//        foreach ($goods_list_arr as $k=>$v){
//            if(isset($v['sku_id']) && $v['sku_id']){
//                $goods_detail = GoodsSkuModel::where(['sku_id'=>$v['sku_id'],'goods_id'=>$v['goods_id']])->find();
//            }else{
//                $goods_detail = GoodsModel::find($v['goods_id']);
//            }
//
//            $origin_price += $goods_detail['original_price']*$v['goods_num'];//原价
//            $vip_price += $goods_detail['vip_price']*$v['goods_num'];//售价
//        }



        if($send_type == 3){

            $city_setting = SendCityModel::where([['shop_id','=',$this->request->shopId]])->json(['send_scope','order_send_time','ladder_freight_distance','reduce_freight_price'],true)->find();
            $send_scope = $city_setting->send_scope;
            $freight = $city_setting->base_freight;//只收取基本配送费

            //基础配送费0，则免费配送
//            if($city_setting->base_freight>0){
//
//                $ladder_freight_distance = $city_setting->ladder_freight_distance;
//
//                //开启阶梯配送距离（距离根据导航距离，非直线距离）
//                if($ladder_freight_distance['is_open']){
//
//                    $origin = $send_scope['lng'].','.$send_scope['lat'];
//                    $destination = $lng.','.$lat;
//                    //$distance = $this->getDistanceBaidu($origin,$destination);
//
//                    $distance = 3;
//                    if($distance > $ladder_freight_distance['base_price_distance']){
//                        $freight += ceil(($distance-$ladder_freight_distance['base_price_distance'])/$ladder_freight_distance['add_km'])*$ladder_freight_distance['freight'];//每超过几公里收多少
//                    }
//
//                }
//
//                $reduce_freight_price = $city_setting->reduce_freight_price;
//
//                //开启阶梯配送满减
//                if($reduce_freight_price['is_open']){
//
//                    if($reduce_freight_price['price_type'] == 1){
//                        //原价满减
//                        $price = $origin_price;
//                    }else if($reduce_freight_price['price_type'] == 2){
//                        //售价满减
//                        $price = $vip_price;
//                    }else{
//                        $price = 0;
//                    }
//
//                    if($price > $reduce_freight_price['full']){
//
//                        if($reduce_freight_price['reduce'] == 1){
//                            //减全部配送费
//                            $freight = 0.00;
//                        }else if($reduce_freight_price['reduce'] == 2){
//                            //减基础配送费
//                            $freight = $freight - $city_setting->base_freight;
//                        }
//                    }
//                }
//
//            }else{
//                $freight = 0.00;
//            }

            $detail = [
                'name'=>$city_setting->name,
                'start_send_price'=>$city_setting->start_send_price,
                'freight'=>(float)sprintf("%.2f",$freight),
                'send_scope'=>$send_scope,
            ];
        }


        return $this->success(['detail'=>$detail]);
    }

    public function getDistanceBaidu($origin,$destination){

        $ak ='plSNfkDGpi5VqyX9TCHwhVQymAkFLVD0';
        $url = "https://api.map.baidu.com/direction/v2/motorcycle?origin={$origin}&destination={$destination}&coord_type=bd09mc&ak={$ak}";
        $result = $this->get($url);
        return $result;
    }

    /**

     * 获取access_token

     * parameter -- $url(String) -- 请求地址

     */

    protected function get($url)

    {

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);

        curl_setopt($curl, CURLOPT_HEADER, 0);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts

        $result = curl_exec($curl);

        curl_close($curl);

        return $result;

    }

    /**
     *计算预约配送时段
     */
    public function open_order_day($day,$week,$forward_time=0){
        $week_arr=[1=>'周一',2=>'周二',3=>'周三',4=>'周四',5=>'周五',6=>'周六',7=>'周天'];
        $day_arr=[];
        $week=array_column($week,null,'week');
        $row=0;
        $time_now=time();
        if($forward_time>0){
            $time_now=time()+$forward_time;
        }
        for ($i=0;$i<49;$i++){
            $time=$time_now+$i*24*3600;
            $date=date('m月d日',$time);
            $week_n=date('w',$time);
            if(!empty($week[$week_n])){
                if($row>$day){
                    break;
                }
                $one['day']=$date.'（'.$week_arr[$week_n].'）';
                $one['date']=date('Y-m-d',$time);
                $one['time']=$week[$week_n];
                $one['time_now']=$time_now;
                $day_arr[]=$one;
                $row++;
            }
        }
        return $day_arr;
    }
    /**
     *计算预约配送时段(一天内的详细时段)
     */
    public function day_time($time,$order_time_slot,$date,$time_now=0){
        $date_time=strtotime($date);
        $today_time=strtotime(date('Y-m-d 00:00:00',time()));
        $start_time=strtotime($time['start_time'])-$today_time;
        $end_time=strtotime($time['end_time'])-$today_time;
        $time_slot=$order_time_slot['time_slot'];
        $time_slot_type=$order_time_slot['time_slot_type'];
        $time_detail=[];
//        if(empty($time_now)){
            $time_now=time();
//        }
        if($time_slot_type==1){//分
            $g_time=$time_slot*60;
        }elseif ($time_slot_type==2){//小时
            $g_time=$time_slot*60*60;
        }elseif ($time_slot_type==3){//天
            $time_detail[]=$time['start_time'].'~'.$time['end_time'];
        }
        if($time_slot_type!=3){
            if (empty($g_time)){
                $g_time=$time_slot*60*60;
            }
            $cha_time=$end_time-$start_time;
            $num=ceil($cha_time/$g_time);
            for ($i=1;$i<=$num;$i++){
                $s_time_str=date('H:i',($date_time+$start_time+($i-1)*$g_time));
                if($i==$num){
                    $e_time_str=date('H:i',($date_time+$end_time));
                }else{
                    $e_time_str=date('H:i',($date_time+$start_time+$i*$g_time));
                }
                if(($date_time+$start_time+($i-1)*$g_time)>=$time_now){
                    $time_str=$s_time_str.'~'.$e_time_str;
                    $time_detail[]=$time_str;
                }
            }
        }
        return $time_detail;
    }
}
